﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InnovTech.Persistence;

namespace NHibernate.Util
{
    public class NHibernateTransactionUnitWorker : IUnitWorker
    {

        private ISession _session;

        public NHibernateTransactionUnitWorker(ISession session)
        {
            _session = session;
        }

        public TResult DoUnitOfWork<TResult>(Func<IDao, TResult> action)
        {
            IDao dao = new NHibernateDao(_session);
            TResult result = default(TResult);

            using (var tran = _session.BeginTransaction())
            {
                try
                {
                    result = action(dao);
                    tran.Commit();
                    return result;
                }
                catch
                {
                    if (tran != null && tran.IsActive)
                        tran.Rollback();
                    throw;
                }
            }
        }
    }
}
